package com.micro.ai.gateway.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

/**
 * 配置变更监听器
 * 监听Nacos配置变更，记录日志和触发相关处理
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Component
public class ConfigChangeListener implements ApplicationListener<EnvironmentChangeEvent> {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onApplicationEvent(@NonNull EnvironmentChangeEvent event) {
        Set<String> keys = event.getKeys();
        
        if (keys == null || keys.isEmpty()) {
            return;
        }

        log.info("========================================");
        log.info("📝 Nacos配置变更事件");
        log.info("========================================");
        log.info("变更时间: {}", LocalDateTime.now().format(formatter));
        log.info("变更配置数量: {}", keys.size());
        log.info("变更配置项:");
        
        keys.forEach(key -> {
            // 根据配置项分类记录
            if (key.startsWith("rate-limit")) {
                log.info("  🚦 限流配置变更: {}", key);
            } else if (key.startsWith("signature")) {
                log.info("  🔐 签名验证配置变更: {}", key);
            } else if (key.startsWith("ip-filter")) {
                log.info("  🛡️ IP过滤配置变更: {}", key);
            } else if (key.startsWith("jwt")) {
                log.info("  🎫 JWT配置变更: {}", key);
            } else if (key.startsWith("logging")) {
                log.info("  📋 日志配置变更: {}", key);
            } else {
                log.info("  ⚙️ 配置变更: {}", key);
            }
        });
        
        log.info("========================================");
        log.info("✅ 配置已刷新并生效");
        log.info("========================================");
    }
}

